using BackData;
using Domain;
using Domain.BOM;
using Domain.DTOs.Quality;
using Domain.RBAC;
using Domain.工艺工序;
using Infratructure;
using MediatR;
using Team.API.Applocation.Command.Quality;

namespace Team.API.Applocation.Hanldler.Quality
{
    /// <summary>
    /// 根据ID获取质检表数据处理器（包含关联数据）
    /// </summary>
    public class FindQualityHandler : IRequestHandler<FindQualityCommand, APIResult<QualityListDto>>
    {
        private readonly IRepository<Qualitymodel> _qualiRep;
        private readonly IRepository<Workmodel> _workRep;
        private readonly IRepository<Bomtable> _bomRep;
        private readonly IRepository<Makestepmodel> _makeRep;
        private readonly IRepository<Usermodel> _userRep;
        private readonly ILogger<FindQualityHandler> _logger;

        public FindQualityHandler(
            IRepository<Qualitymodel> qualiRep,
            IRepository<Workmodel> workRep,
            IRepository<Bomtable> bomRep,
            IRepository<Makestepmodel> makeRep,
            IRepository<Usermodel> userRep,
            ILogger<FindQualityHandler> logger)
        {
            _qualiRep = qualiRep;
            _workRep = workRep;
            _bomRep = bomRep;
            _makeRep = makeRep;
            _userRep = userRep;
            _logger = logger;
        }

        public async Task<APIResult<QualityListDto>> Handle(FindQualityCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询质检工单
                var quality = await _qualiRep.GetByIdAsync(request.Id);
                
                if (quality == null || quality.IsDel)
                {
                    return new APIResult<QualityListDto>
                    {
                        Code = StateCode.Fail,
                        Message = "质检工单不存在",
                        Result = null
                    };
                }

                // 分别查询关联数据
                Workmodel work = null;
                if (quality.Orderid > 0)
                {
                    var workList = _workRep.GetAll().Where(w => w.Id == quality.Orderid && w.IsDel == false).ToList();
                    work = workList.FirstOrDefault();
                }
                
                Bomtable bom = null;
                if (quality.Itemid > 0)
                {
                    var bomList = _bomRep.GetAll().Where(b => b.Id == quality.Itemid && b.IsDel == false).ToList();
                    bom = bomList.FirstOrDefault();
                }
                
                Makestepmodel make = null;
                if (quality.Processid > 0)
                {
                    var makeList = _makeRep.GetAll().Where(m => m.Id == quality.Processid && m.IsDel == false).ToList();
                    make = makeList.FirstOrDefault();
                }
                
                Usermodel user = null;
                if (quality.Accountid > 0)
                {
                    var userList = _userRep.GetAll().Where(u => u.Id == quality.Accountid && u.IsDel == false).ToList();
                    user = userList.FirstOrDefault();
                }

                // 组装DTO
                var result = new QualityListDto
                {
                    Id = quality.Id,
                    Quaworksubject = quality.Quaworksubject ?? "",
                    Quaworkcode = quality.Quaworkcode ?? "",
                    Quaworkname = quality.Quaworkname ?? "",
                    Orderid = quality.Orderid,
                    WorkCode = work?.Quaworkcode ?? "",
                    Completenum = quality.Completenum,
                    Qualifiednum = quality.Qualifiednum,
                    Defectivenum = quality.Defectivenum,
                    Itemid = quality.Itemid,
                    Goodsname = bom?.Goodsname ?? "",
                    Status = quality.Status,
                    Processid = quality.Processid,
                    Processcount = quality.Processcount,
                    Reportingcount = quality.Reportingcount,
                    Inspectioncount = quality.Inspectioncount,
                    Reportingtime = quality.Reportingtime,
                    Accountid = quality.Accountid,
                    QualityUsername = user?.RealName ?? "",
                    Meeage = quality.Meeage ?? "",
                    Createtime = quality.Createtime,
                    Updatetime = quality.Updatetime
                };

                return new APIResult<QualityListDto>
                {
                    Code = StateCode.OK,
                    Message = "获取质检工单成功",
                    Result = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError($"获取质检工单失败: {ex.Message}");
                return new APIResult<QualityListDto>
                {
                    Code = StateCode.Fail,
                    Message = $"获取质检工单失败: {ex.Message}",
                    Result = null
                };
            }
        }
    }
}
